<template>
  <div>
    <div class="container" v-if="isList">
      <!-- 添加按钮区 -->
      <div class="btn_zone">
        <el-row style="align-items: center; text-align: center;">
          <el-col :span="1">
            <el-button type="primary" @click="handleAddTeacher">添加老师</el-button>
          </el-col>
        </el-row>
      </div>
      <el-divider />
      <!-- 表格区 -->
      <div class="tbl_zone">
        <el-table
          :data="pagedData"
          style="width: 100%;"
          size="large"
          v-loading="loading"
          border
        >
          <el-table-column type="index" label="#" width="60" :index="indexMethod" />
          <el-table-column prop="name" label="老师名" sortable width="90" />
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="scope">
              {{ scope.row.gender === 'M' ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="contactPhone" label="手机号码" sortable width="140" />
          <el-table-column prop="email" label="邮箱" width="210" />
          <el-table-column prop="specialty" label="擅长" width="100" />
          <el-table-column prop="hireDate" label="入职日期" width="120" />
          <el-table-column prop="status" label="在职" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status ? 'success' : 'info'">
                {{ scope.row.status ? '在职' : '离职' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="90">
            <template #default="scope">
              <!-- 删除“查看详情”按钮 -->
              <el-button link type="success" @click="handleEdit(scope.row)">
                编辑&nbsp;<el-icon><Edit /></el-icon>
              </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)">
                删除&nbsp;<el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next, jumper"
            :total="tableData.length"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </div>

      <!-- 抽屉区 -->
      <el-drawer v-model="drawer" direction="rtl" size="50%">
        <template #header="{ titleId, titleClass }">
          <h2 :id="titleId" :class="titleClass">{{ drawerTitle }}</h2>
        </template>
        <!-- 添加/编辑表单 -->
        <el-form
          ref="teacherFormRef"
          style="max-width: 600px"
          :model="teacherForm"
          :rules="rules"
          label-width="auto"
          class="add_teacher_form"
          status-icon
        >
          <el-form-item label="老师姓名" prop="name">
            <el-input v-model="teacherForm.name" />
          </el-form-item>
          <el-form-item label="手机号" prop="contactPhone">
            <el-input v-model="teacherForm.contactPhone" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="teacherForm.email" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="teacherForm.gender">
              <el-radio value="M">男</el-radio>
              <el-radio value="F">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="擅长" prop="specialty">
            <el-input v-model="teacherForm.specialty" />
          </el-form-item>
          <el-form-item label="入职日期" prop="hireDate">
            <el-date-picker v-model="teacherForm.hireDate" type="date" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
          <el-form-item label="在职" prop="status">
            <el-switch v-model="teacherForm.status" active-text="在职" inactive-text="离职" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(teacherFormRef)">
              {{ drawerTitle.includes('添加') ? '添加' : '保存' }}
            </el-button>
            <el-button @click="resetForm(teacherFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
    </div>
    <TeacherDetail v-else v-model:isList="isList" :id="idd" />
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'
import TeacherDetail from '@/views/teacher/TeacherDetail.vue'

const tableData = ref([])
const isList = ref(true)
const loading = ref(false)

const pageSize = 5
const currentPage = ref(1)
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return tableData.value.slice(start, start + pageSize)
})

const handlePageChange = (page) => {
  currentPage.value = page
}

const fetchTeachers = async () => {
  loading.value = true
  try {
    const { data } = await axios.get('http://localhost:8080/api/teachers')
    // 确保 data 里的每个 teacher 都有 teacherId 字段
    tableData.value = data.data || data
    console.log('老师数据', tableData.value)
  } catch (error) {
    ElMessage.error('加载老师数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(fetchTeachers)

const drawer = ref(false)
const drawerTitle = ref('添加老师')

const teacherFormRef = ref()
const teacherForm = reactive({
  teacherId: '',
  name: '',
  contactPhone: '',
  email: '',
  gender: '',
  specialty: '',
  hireDate: '',
  status: true,
  description: ''
})

const rules = reactive({
  name: [
    { required: true, message: '请输入老师姓名', trigger: 'blur' },
    { min: 2, max: 12, message: '姓名长度在2-12之间', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  hireDate: [
    { type: 'date', required: true, message: '请选择入职日期', trigger: 'change' }
  ]
})

const handleAddTeacher = () => {
  drawer.value = true
  drawerTitle.value = '添加老师'
  Object.assign(teacherForm, {
    teacherId: '',
    name: '',
    contactPhone: '',
    email: '',
    gender: '',
    specialty: '',
    hireDate: '',
    status: true,
    description: ''
  })
}

const handleEdit = (row) => {
  if (!row.teacherId) {
    ElMessage.error('该老师数据缺少 teacherId，无法编辑')
    return
  }
  drawerTitle.value = '编辑老师'
  drawer.value = true
  Object.assign(teacherForm, JSON.parse(JSON.stringify(row)))
}

const handleDelete = async (row) => {
  if (!row.teacherId) {
    ElMessage.error('该老师数据缺少 teacherId，无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除该老师吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await axios.delete(`http://localhost:8080/api/teachers/${row.teacherId}`)
    ElMessage.success('删除成功')
    fetchTeachers()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const teacherFormSubmitApi = async (form) => {
  if (drawerTitle.value.includes('添加')) {
    await axios.post('http://localhost:8080/api/teachers', form)
  } else {
    await axios.put(`http://localhost:8080/api/teachers/${form.teacherId}`, form)
  }
  fetchTeachers()
}

const submitForm = async (formElement) => {
  if (!formElement) return
  await formElement.validate(async (valid) => {
    if (valid) {
      await teacherFormSubmitApi(teacherForm)
      drawer.value = false
      ElMessage.success(drawerTitle.value.includes('添加') ? '添加成功' : '保存成功')
    }
  })
}

const resetForm = (formElement) => {
  if (!formElement) return
  formElement.resetFields()
}

const router = useRouter()
const idd = ref()
const handleDetail = (id) => {
  isList.value = false
  idd.value = id
}

function indexMethod(index) {
  return (currentPage.value - 1) * pageSize + index + 1
}
</script>

<style scoped>
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-start;
}
.add_teacher_form {
  margin: 5px 50px;
}
.btn_zone {
  margin-top: -19px;
}
</style>